package com.kitty.mybatis.mybatisv1.binding;

import com.kitty.mybatis.mybatisv1.session.KittyConfiguration;
import com.kitty.mybatis.mybatisv1.session.KittySqlSession;
import com.kitty.mybatis.mybatisv1.exceptions.BindingException;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author SHEN
 * @Date 2020/10/21
 */
public class KittyMapperRegistry {
    //private KittyConfiguration configuration;

    private final Map<Class<?>,KittyMapperProxyFactory<?>> knowmappers =new HashMap<>();

    public KittyMapperRegistry(KittyConfiguration configuration) {
        //this.configuration = configuration;
    }

    public <T> T getMapper(Class<?> clazz, KittySqlSession sqlSession){
        final KittyMapperProxyFactory<T> mapperProxyFactory = (KittyMapperProxyFactory<T>) knowmappers.get(clazz);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + clazz + " is not known to the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new BindingException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    public <T> void addMapper(Class<T> clazz){
        if(clazz.isInterface()){
            if(hasMapper(clazz)){
                throw new BindingException("KittyMapperRegistry已经包含"+clazz);
            }
            knowmappers.put(clazz,new KittyMapperProxyFactory<>(clazz));
        }
    }

    public <T> boolean hasMapper(Class<T> clazz){
        return knowmappers.containsKey(clazz);
    }

}
